package model

import (
	"errors"
	"fmt"

	"github.com/hwcer/cosgo"
	"github.com/hwcer/cosmo"
	"github.com/hwcer/yyds/options"
)

var (
	db *cosmo.DB
	//Redis  *redis.Client
	Embed  bool
	models []any
)

var Options = struct {
	Redis   string `json:"redis"`
	Mongodb string `json:"mongodb"`
}{}

func init() {
	cosgo.On(cosgo.EventTypLoaded, func() error {
		for _, model := range models {
			db.Register(model)
		}
		return nil
	})
}

func DB() *cosmo.DB {
	return db
}

func SetEmbed(mongo *cosmo.DB) {
	db = mongo
	//Redis = redis
	Embed = true
}

func Register(i ...any) {
	models = append(models, i...)
}

func Start() (err error) {
	if Embed {
		return
	}
	db = cosmo.New()
	if Options.Mongodb == "" {
		return errors.New("mongodb address is required")
	}
	if err = db.Start(fmt.Sprintf("%v#%v", options.Options.Appid, options.ServiceTypeSocial), Options.Mongodb); err != nil {
		return
	}

	return
}
